<template>
    <el-card shadow="never" class="border-0">
        <!-- 项目详情 -->
        <el-form :model="form_project" ref="formRef_project"  :rules="rules_project" label-width="80px" :inline="false">
            <el-row>
                <el-col :span="10">
                    <el-form-item label="项目名称" prop="projectName" >
                        <el-input :disabled="!form_project_edit_flag" v-model="form_project.projectName" placeholder="项目名称"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="10">
                    <el-form-item label="客户公司" prop="customerId">
                        <el-button :disabled="!form_project_edit_flag" @click="setSelectCompanyId('project')">{{ checkedCustomer_project?.name }}</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
                <el-col :span="12">
                    <el-form-item label="位置信息" prop="formattedAddress">
                        <el-button :disabled="!form_project_edit_flag" @click="clickSetLocationBtn_project">{{ form_project.formattedAddress==null ? '点击获取项目位置' : form_project.formattedAddress }}</el-button>
                    </el-form-item>
                </el-col>
            </el-row> -->
           
            <el-row>
                <el-col :span="6">
                    <el-form-item label="开始时间" prop="startTime">
                        <el-date-picker
                            :disabled="!form_project_edit_flag"
                            v-model="form_project.startTime"
                            type="date"
                            placeholder="开始时间"
                            format="YYYY-MM-DD" 
                            value-format="YYYY-MM-DD">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="结束时间" prop="startTime">
                        <el-date-picker
                            :disabled="!form_project_edit_flag"
                            v-model="form_project.endTime"
                            type="date"
                            placeholder="开始时间"
                            format="YYYY-MM-DD" 
                            value-format="YYYY-MM-DD">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="10" >
                    <el-form-item label="项目描述" prop="projectDescription">
                        <el-input :disabled="!form_project_edit_flag" v-model="form_project.projectDescription" placeholder="项目描述" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            
        </el-form>
        <el-row>
            <el-switch
                v-model="form_project_edit_flag"
                size="small"
                active-text="编辑"
                inactive-text="只读"
            />
            <!-- <el-button type="primary" size="small" @click="updateProject_edit_flag">{{ form_project_edit_flag ? '编辑模式' : '只读模式' }}</el-button> -->
            <el-button class="mx-2" type="primary" size="small" :disabled="!form_project_edit_flag" @click="updateProject">修改项目</el-button>
            <el-popconfirm title="是否要删除该项目？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleDelete_project">
                            <template #reference>
                                <el-button size="small" type="primary" :disabled="!form_project_edit_flag">删除</el-button>
                            </template>
                        </el-popconfirm>
        </el-row>
        <el-divider />
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="5" :offset="0">
                    <el-form-item label="工单名称">
                        <el-input v-model="searchForm.orderName" placeholder="工单名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="工单状态">
                        <el-select v-model="searchForm.orderStatus" placeholder="工单状态">
                            <el-option v-for="item in orderStatusList" :key="item.code" :label="item.description"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>


        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="getData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 工单table -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
            <!-- <el-table-column label="工单ID" prop="orderId"></el-table-column> -->
            <el-table-column label="工单名称" align="center" prop="orderName"></el-table-column>
            <el-table-column label="工单类型" align="center">
                <template #default="{ row }">
                    {{ formatOrderType(row.orderType) }}
                </template>
            </el-table-column>
            <!-- <el-table-column label="项目ID" prop="projectId"></el-table-column> -->
            <!-- <el-table-column label="客户ID" prop="customerId"></el-table-column> -->
            <el-table-column label="工单金额" align="center" prop="sum"></el-table-column>
            <el-table-column label="工单状态" align="center">
                <template #default="{ row }">
                    {{ formatOrderStatus(row.orderStatus) }}
                </template>
            </el-table-column>
            <!-- <el-table-column label="分配工程师" align="center" prop="engineerName"></el-table-column> -->
            <!-- <el-table-column label="客户评分" align="center" prop="customerRating"></el-table-column> -->
            <el-table-column label="开始时间" align="center" prop="startTime"> </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime"> </el-table-column>
            <el-table-column label="工单描述" align="center" prop="orderDescription" show-overflow-tooltip></el-table-column>

            <el-table-column label="操作" width="200" align="center">
                <template #default="scope">
                    <div>
                        <el-button type="primary" text size="small"  @click="handleEdit(scope.row)">修改</el-button>
                        <!-- 未指派的状态指派按钮可用，其他场景不可用 -->
                        <el-button v-if="scope.row.orderStatus < 6" type="primary" text size="small"  @click="handleAssign(scope.row)">指派</el-button>
                        <el-button v-else type="primary" text size="small" disabled>指派</el-button>

                        <el-button v-if="scope.row.orderType!=3" type="primary" text size="small"  @click="handleOrderLog(scope.row)">日志</el-button>
                        <el-button v-else type="primary" text size="small" disabled>日志</el-button>


                        <el-popconfirm title="是否要确认回款？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleOrderPayment(scope.row.orderId)">
                            <template #reference>
                                <!-- 施工已结束的工单才可以进行回款确认 -->
                                <el-button v-if="scope.row.orderStatus==6 || (scope.row.orderType==3 && scope.row.orderStatus==1)" type="primary" text size="small">回款</el-button>
                                <el-button v-else type="primary" text size="small" disabled>回款</el-button>
                            </template>
                        </el-popconfirm>

                        <el-popconfirm title="是否要确认结单？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleOrderOver(scope.row.orderId)">
                            <template #reference>
                                <!-- 已回款的工单才可以进行结束工单 -->
                                <el-button v-if="scope.row.orderStatus==7 || (scope.row.orderType==3 && scope.row.orderStatus==7)" type="primary" text size="small">结单</el-button>
                                <el-button v-else type="primary" text size="small" disabled>结单</el-button>
                            </template>
                        </el-popconfirm>

                        <!-- 已完结状态的工单才可以进行评分 -->
                        <el-button v-if="scope.row.orderStatus==8" type="primary" text size="small"  @click="handleScore(scope.row)">内部评分</el-button>
                        <el-button v-else type="primary" text size="small"  @click="handleScore(scope.row)" disabled>内部评分</el-button>

                        <el-button type="primary" text size="small"  @click="customerScore(scope.row)">客户评分</el-button>

                        <el-button type="primary" text size="small"  @click="showFilesEn(scope.row)">施工档案</el-button>

                        <el-button type="primary" text size="small"  @click="showFiles(scope.row)">附件</el-button>

                        <el-popconfirm title="是否要删除该工单？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleDelete(scope.row.orderId)">
                            <template #reference>
                                <!-- 未指派的状态删除按钮可用，其他场景不可用 -->
                                <el-button v-if="scope.row.orderStatus==1" text type="primary" size="small">删除</el-button>
                                <el-button v-else text type="primary" size="small" disabled>删除</el-button>
                            </template>
                        </el-popconfirm>

                        <!-- <el-popconfirm title="确认生成报告吗？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleReport(scope.row.orderId)">
                            <template #reference>
                                <el-button v-if="scope.row.orderStatus==8" text type="primary" size="small" disabled>报告</el-button>
                                <el-button v-else text type="primary" size="small" disabled>报告</el-button>
                            </template>
                        </el-popconfirm> -->
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 工单table分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" 
            :current-page="currentPage"
            :page-size="limit" 
            @current-change="getData" />
        </div>

        <!-- 新增工单 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="90px" :inline="false">
                <el-form-item label="工单名称" prop="orderName">
                    <el-input v-model="form.orderName" placeholder="工单名称"></el-input>
                </el-form-item>
                <el-form-item label="船名/船号" prop="vessleName">
                    <el-input v-model="form.vessleName" placeholder="船名/船号"></el-input>
                </el-form-item>
                <el-form-item label="服务要求" prop="serviceRequest">
                    <el-input v-model="form.serviceRequest" placeholder="服务要求"></el-input>
                </el-form-item>
                <el-form-item label="工单类型" prop="orderType">
                    <el-select v-model="form.orderType" filterable placeholder="工单类型">
                        <el-option v-for="item in orderTypes" :key="item.code" :label="item.description"
                            :value="item.code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工单金额" prop="sum">
                    <el-input-number v-model="form.sum" placeholder="工单金额" :min=0></el-input-number> <span class="px-2">元</span>
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                        v-model="form.startTime"
                        type="date"
                        placeholder="开始时间"
                        format="YYYY-MM-DD" 
                        value-format="YYYY-MM-DD">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                        v-model="form.endTime"
                        type="date"
                        placeholder="结束时间"
                        format="YYYY-MM-DD" 
                        value-format="YYYY-MM-DD">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="位置信息" prop="formattedAddress">
                    <el-button @click="clickSetLocationBtn">{{ form.formattedAddress==null ? '点击获取位置' : form.formattedAddress }}</el-button>
                </el-form-item>
                <el-form-item label="工单描述" prop="orderDescription">
                    <el-input v-model="form.orderDescription" type="textarea" :rows="2" placeholder="工单描述"></el-input>
                </el-form-item>
            </el-form>
        </FormDrawer>

        <!-- 工单管理员评价 -->
        <FormDrawer ref="formDrawerRef_score" title="内部评分" @submit="handleSubmit_score">
            <!-- <el-form-item label="订单号" label-width="150px">
                <el-input v-model="form_score.orderId" disabled></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="综合评分" label-width="150px">
                <el-rate v-if="form_score.isEdit==true" v-model="form_score.mark"  />
                <el-rate v-else v-model="form_score.mark" disabled/>
            </el-form-item> -->
            <el-form-item 
                v-for="item in form_score.labelMarks" 
                :label="item.labelName" 
                label-width="150px" 
                label-position="left">
                <el-rate v-if="form_score.isEdit==true" v-model="item.mark"/>
                <el-rate v-else v-model="item.mark" disabled/>
            </el-form-item>
            <el-form-item label="工单评价" label-width="150px">
                <el-input v-if="form_score.isEdit==true" type="textarea" :rows="4" v-model="form_score.remark" placeholder="工单评价"></el-input>
                <el-input v-else type="textarea" :rows="4" v-model="form_score.remark" placeholder="工单评价" disabled></el-input>
            </el-form-item>
        </FormDrawer>

        <!-- 客户评分 -->
        <FormDrawer  showSubBtn="0" ref="formDrawerRef_customerScore" title="客户评分">
            <h3>现场人员评分</h3>
            <el-form-item 
                v-for="item in form_customerScore.labelMarks" 
                :label="item.labelName" 
                label-position="left">
                <el-rate v-model="item.mark" disabled/>
            </el-form-item>
            <el-form-item label="工单评价">
                <el-input type="textarea" :rows="4" v-model="form_customerScore.remark" placeholder="工单评价" disabled></el-input>
            </el-form-item>
        </FormDrawer>

    </el-card>

    <!-- 查看工单日志 -->
    <el-dialog v-model="dialogTableVisible_orderLog" title="查看日志" width="70%" align-center>
        <OrderLog v-if="dialogTableVisible_orderLog" :orderDetail="currOrderLog_orderDetail"  />
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogTableVisible_orderLog = false">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 选取客户dialog -->
    <el-dialog v-model="dialogTableVisible_customer" title="选择客户" width="70%" align-center>
        <SelectCompany :showSelection="true" :selectedCompanyId="selectCompanyConfig.id" @getCheckedCompany="getCheckedCompany" />
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogTableVisible_customer = false">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 选取位置dialog -->
    <SystemDialog title="选取地点坐标" :visible="setLocationDialogVisible" :height="400" :width="800" @on-close="closeAddress"
        @on-confirm="commitAddress">
        <template v-slot:content>
            <el-form-item label="位置">
                <GaoDeMap :addressClick="addressClick" ref="mapRef" @address="getAddress"></GaoDeMap>
            </el-form-item>
        </template>
    </SystemDialog>

    <!-- 选取工程师dialog -->
    <SystemDialog title="指派工程师" :visible="asignEngineerDialogVisible" :height="600" :width="1200" @on-close="closeAssignEngineer"
        @on-confirm="commitAssignEngineer">
        <template v-slot:content>
            <!-- <GaodeEngineerMap :assignProps="assignProps" ></GaodeEngineerMap> -->
            <SelectEngineer v-if="asignEngineerDialogVisible" :assignProps="assignProps"></SelectEngineer>
        </template>
    </SystemDialog>

    <!-- 附件弹窗 -->
    <el-dialog v-model="dialogTableVisible_orderFiles" :title="dialogTable_orderFiles_title" width="700" align-center>
        <OrderFiles v-if="dialogTableVisible_orderFiles" :orderId="currOrderFiles_orderId" :fileType="dialogTable_orderFiles_type"/>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogTableVisible_orderFiles = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, computed, onMounted, onUpdated, watch } from "vue"
import FormDrawer from "~/components/FormDrawer.vue";
import SelectCompany from "~/components/select-company.vue";
import SelectEngineer from "~/components/select-engineer.vue";
import { api_orders_add, api_orders_detail, api_orders_getScore, api_orders_list, api_orders_postScore, api_orders_scoreLabels, api_orders_update, api_project_constant, 
    api_orders_delete, api_orders_customerScoreLabels, api_orders_getCustomerScore} from "~/api/ordersApi"
import { toast, toastWarn } from "~/composables/util"
import { api_project_delete, api_project_detail, api_project_update } from "~/api/projectApi";
import GaoDeMap from "~/components/GaoDeMap.vue";
import GaodeEngineerMap from "~/components/GaodeEngineerMap.vue";
import SystemDialog from "~/components/SystemDialog.vue";
import OrderLog from "./order-log.vue";
import OrderFiles from "./order-files.vue";

//props，父子传参：项目ID
const props = defineProps({
    projectId: [Number, String],
})

// 页面变量
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const selectCompanyConfig = ref({
    id: null,
    type: 'project' // 当前谁在用这个弹出框 project, order
})

const searchForm = reactive({
    orderName: "",
    projectId: props.projectId,
    customerId: "",
    orderStatus: null,
    customerRating: null,
    page: currentPage.value,
    size: limit.value,
    startTime: '',
    endTime: '',
})
const resetSearchForm = () => {
    searchForm.orderName = ""
    searchForm.projectId = ""
    searchForm.customerId = ""
    searchForm.orderStatus = null
    searchForm.customerRating = null
    getData()
}


const tableData = ref([])
const loading = ref(false)
const orderStatusList = ref([])
const orderTypes = ref([])
const engineerStatusList = ref([])
const dialogTableVisible_customer = ref(false)
const checkedCustomer = ref(null)
const checkedCustomer_project = ref(null)


// 客户评分------------
const formDrawerRef_customerScore = ref(null)
const form_customerScore = reactive({
    orderId: null,
    remark: "",
    labelMarks: []
})
// 客户评分------------
const formDrawerRef = ref(null)
const formDrawerRef_score = ref(null)
const dialogTableVisible_orderLog = ref(false)
const currOrderLog_orderDetail = ref(null)
const dialogTable_orderFiles_title = ref(null)
const dialogTable_orderFiles_type = ref(null)
const dialogTableVisible_orderFiles = ref(false)
const currOrderFiles_orderId = ref(null)

const formRef = ref(null)
const form = reactive({
    orderId: null,
    orderName: "",
    orderDescription: "",
    projectId: props.projectId,
    //工单客户信息与项目一致
    customerId: checkedCustomer_project.value==null?"":checkedCustomer_project.value.id,
    sum: 0,
    orderType: null,
    //用于位置校验
    formattedAddress: null,
    locationCreateDto: {
        latitude: null,
        longitude: null,
        locationType: "1",
        formattedAddress: "",
        adcode: "",
        country: "",
        province: "",
        city: "",
        district: "",
        township: ""
    },
    startTime: null,
    endTime: null,
    serviceRequest: null,
    vessleName: null
})

const rules_project = {
    projectName: [
        { required: true, message: '项目名称不能为空', trigger: 'change' }
    ],
    // projectDescription: [
    //     { required: true, message: '项目描述不能为空', trigger: 'change' }
    // ],
    customerId: [
        { required: true, message: '客户公司不能为空', trigger: 'change' }
    ],
    // startTime: [
    //     { required: true, message: '开始时间不能为空', trigger: 'change' }
    // ],
    // endTime: [
    //     { required: true, message: '结束时间不能为空', trigger: 'change' }
    // ],
    formattedAddress: [
        { required: true, message: '位置信息不能为空', trigger: 'change' }
    ]
}

const rules = {
    orderName: [
        { required: true, message: '工单名称不能为空', trigger: 'change' }
    ],
    // orderDescription: [
    //     { required: true, message: '工单描述不能为空', trigger: 'change' }
    // ],
    orderType: [
        { required: true, message: '工单类型不能为空', trigger: 'change' }
    ],
    sum: [
        { required: true, message: '工单金额不能为空', trigger: 'change' }
    ],
    // startTime: [
    //     { required: true, message: '工单开始时间不能为空', trigger: 'change' }
    // ],
    // endTime: [
    //     { required: true, message: '工单结束时间不能为空', trigger: 'change' }
    // ],
    formattedAddress: [
        { required: true, message: '位置信息不能为空', trigger: 'change' }
    ],
    serviceRequest: [
        { required: true, message: '服务要求不能为空', trigger: 'change' }
    ],
    vessleName: [
        { required: true, message: '船名/船号不能为空', trigger: 'change' }
    ]
}
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const address = ref("点击设置位置");
const address_project = ref("点击设置位置");
const setLocationDialogVisible = ref(false)
const choseLocationFlag = ref(null)
const setLocationDialogVisible_project = ref(false)
const asignEngineerDialogVisible = ref(false)
const orderLocation = ref(null)
const assignProps = ref(null)
const form_score = reactive({
    //是否可编辑
    isEdit: false,
    orderId: null,
    mark: 1,
    remark: "",
    labelMarks: []

})
const formRef_project = ref(null)
const form_project = reactive({
    projectId: null,
    projectName: "",
    projectDescription: "",
    projectLocationId: null,
    customerId: null,
    projectStatus: null,
    startTime: null,
    endTime: null,
    serviceRequest: null,
    vessleName: null,
    //用于位置校验
    formattedAddress: null,
    locationCreateDto: {
        latitude: null,
        longitude: null,
        locationType: "1",
        formattedAddress: "",
        adcode: "",
        country: "",
        province: "",
        city: "",
        district: "",
        township: "",

    }
})
const form_project_edit_flag = ref(false) // 当前是否是编辑模式

// 设置选择公司id
const setSelectCompanyId = async (type) => {

    let id = null;
    if (type == 'project') {
        if (!form_project_edit_flag.value) {
            toastWarn('当前项目只读')
            return
        }
        id = form_project.customerId
    } else if (type == 'order') {
        id = form.customerId
    } else {
        return
    }
    console.log('curr company id :', id)
    selectCompanyConfig.value = {id, type}
    dialogTableVisible_customer.value = true
    
    
}

// 提交地图地址
const commitAddress = () => {
    // 提交地图地址
    // 关闭地图
    setLocationDialogVisible.value = false;
    setLocationDialogVisible_project.value = false;
    // console.log('address', address);

}

// 关闭地图
const closeAddress = () => {
    address.value = "";
    // 关闭地图
    setLocationDialogVisible.value = false;
}

// 提交指派工程师
const commitAssignEngineer = () => {
    asignEngineerDialogVisible.value = false;
}

// 关闭指派工程师
const closeAssignEngineer = () => {
    // 关闭地图
    asignEngineerDialogVisible.value = false;
    //重新加载数据
    getData()
}
// 点击设置位置信息btn
function clickSetLocationBtn() {
    setLocationDialogVisible.value = true;
    choseLocationFlag.value = 'order'
}
function clickSetLocationBtn_project() {
    if (!form_project_edit_flag.value) {
        toastWarn('当前项目只读')
        return
    }
    setLocationDialogVisible.value = true;
    choseLocationFlag.value = 'project'
}

// 获取选取位置
const getAddress = (data) => {
    if (data != "") {
        if (choseLocationFlag.value == 'project') {
            address_project.value = data;
            form_project.formattedAddress = data;
        } else {
            address.value = data;
            form.formattedAddress = data;
        }
        
    }
}

// 地图选位置
function addressClick(item, lng, lat) {
    if (choseLocationFlag.value == 'project') {
        address_project.value = `${item.regeocode.formattedAddress}`;
        form_project.formattedAddress = `${item.regeocode.formattedAddress}`;
        form_project.locationCreateDto = {
            latitude: lat,
            longitude: lng,
            locationType: "1",
            formattedAddress: item.regeocode.formattedAddress,
            adcode: item.regeocode.addressComponent.adcode,
            country: item.regeocode.addressComponent.country,
            province: item.regeocode.addressComponent.province,
            city: item.regeocode.addressComponent.city,
            district: item.regeocode.addressComponent.district || item.regeocode.addressComponent.province,
            district: item.regeocode.addressComponent.township,
        }
    } else {
        address.value = `${item.regeocode.formattedAddress}`;
        form.formattedAddress = `${item.regeocode.formattedAddress}`;
        form.locationCreateDto = {
            latitude: lat,
            longitude: lng,
            locationType: "1",
            formattedAddress: item.regeocode.formattedAddress,
            adcode: item.regeocode.addressComponent.adcode,
            country: item.regeocode.addressComponent.country,
            province: item.regeocode.addressComponent.province,
            city: item.regeocode.addressComponent.city,
            district: item.regeocode.addressComponent.district || item.regeocode.addressComponent.province,
            district: item.regeocode.addressComponent.township,
        }
    }
    
}

// 转换订单状态函数
const formatOrderStatus = (state) => {
    return orderStatusList.value.find(x => x.code == state).description
}

// 转换工单类型函数
const formatOrderType = (state) => {
    return orderTypes.value.find(x => x.code == state).description
}

// 生命周期函数
onMounted(() => {

    getData()

    // getRoleList().then(res => {
    //   roles.value = res.records
    // })

    getProjectConstant()
    
    // 获取项目list？？？ 是否需要
    // getProjectList()

    // 获取客户list？？？ 是否需要
    // getCustomerList()

    loadProjectDetail()

    // console.log('order projectId ', form.projectId)

})

watch(
    () => props.projectId, 
    (newProps) => {
        console.log('new props: ', newProps)
        searchForm.projectId = newProps.projectId
        form.projectId = newProps.projectId
        getData()
        loadProjectDetail()
    }
)

// onUpdated(() => {
//     console.log('onUpdated----------------')
//     getData()
// })

// 获取选择的客户
function getCheckedCompany(data) {
    console.log('checked customer: ', data)
    if (data != null) {
        if (selectCompanyConfig.value.type == 'project') {
            form_project.customerId = data.id
            checkedCustomer_project.value = data
        } else if (selectCompanyConfig.value.type == 'order') {
            form.customerId = data.id
            checkedCustomer.value = data
        }
        
    }

}

// 获取订单状态
function getProjectConstant() {
    api_project_constant().then(res => {
        orderStatusList.value = res?.orderStatuses
        engineerStatusList.value = res?.engineerStatuses
        orderTypes.value = res?.orderTypes
    })
}


// 获取数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }
    loading.value = true
    //项目id
    searchForm.projectId = props.projectId
    searchForm.page = currentPage.value
    api_orders_list(searchForm)
        .then(res => {
            // console.log('order list: ', res)
            tableData.value = res.records
            total.value = res.total
            currentPage.value = res.current
        })
        .finally(() => {
            loading.value = false
        })
}



// 删除工单
const handleDelete = (id) => {
    loading.value = true
    api_orders_delete(id).then(res => {
        toast("删除成功")
        getData()
    })
    .finally(() => {
        loading.value = false
    })
}

// 生成报告
const handleReport = (id) => {
    loading.value = true
}

const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) return
        formDrawerRef.value.showLoading()
        const fun = editId.value ? api_orders_update(editId.value, form) : api_orders_add(form)
        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        })
            .finally(() => {
                formDrawerRef.value.hideLoading()
            })

    })
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 新增
const handleCreate = () => {
    editId.value = 0
    resetForm({
        orderId: null,
        orderName: "",
        orderDescription: "",
        projectId: props.projectId,
        //工单客户信息与项目一致
        customerId: checkedCustomer_project.value==null?"":checkedCustomer_project.value.id,
        locationCreateDto: {
            latitude: null,
            longitude: null,
            locationType: "1",
            formattedAddress: "",
            adcode: "",
            country: "",
            province: "",
            city: "",
            district: "",
            township: "",

        }
    })
    //默认工单金额0
    form.sum = 0
    formDrawerRef.value.open()
}

// 编辑
const handleEdit = async(row) => {
    editId.value = row.orderId
    // 根据id查询工单
    let detail = await api_orders_detail(row.orderId)

    console.log('order detail :', detail)

    resetForm(row)
    form.locationCreateDto = { ...detail.orderLocationDto}
    address.value = form.locationCreateDto.formattedAddress
    form.formattedAddress = form.locationCreateDto.formattedAddress
    formDrawerRef.value.open()
}
// 点击指派按钮
const handleAssign = (row) => {
    // console.log('点击指派 按钮')
    let detail = api_orders_detail(row.orderId)
    .then(res => {
        console.log('order detail: ', res)
        assignProps.value = res
        asignEngineerDialogVisible.value = true
    }).catch(err => {
        console.log('查询订单详情错误：', err)
    })
}
// 点击评分按钮
const handleScore = async(row) => {
    //清空数据
    form_score.remark = ""
    form_score.labelMarks = []

    form_score.orderId = row.orderId
    // 查看之前评分
    let detail = await api_orders_getScore(row.orderId)
    if (detail) {
        for (const key in form_score) {
            form_score[key] = detail[key]
        }
        formDrawerRef_score.value.hideSubmitBtn()
        //已评价不可编辑
        form_score.isEdit = false
    } else {
        formDrawerRef_score.value.showSubmitBtn()
        let data = await api_orders_scoreLabels()
        form_score.labelMarks = data.map(x => {
            return {labelId: x.id, mark: 5, labelName: x.value}
        } )
        //未评价可编辑
        form_score.isEdit = true
    }
    formDrawerRef_score.value.open()
}

// 点击查看客户评分
const customerScore = async(row) => {
    //清空数据
    form_customerScore.remark = ""
    form_customerScore.labelMarks = []

    form_customerScore.orderId = row.orderId
    // 查看之前评分
    let detail = await api_orders_getCustomerScore(row.orderId,0)
    if (detail) {
        for (const key in form_customerScore) {
            form_customerScore[key] = detail[key]
        }
        //如果有则打开弹窗
        formDrawerRef_customerScore.value.open()
    } else {
        toastWarn("客户尚未评分!")
    }
}

// 点击日志按钮
const handleOrderLog = (row) => {
    currOrderLog_orderDetail.value = row
    dialogTableVisible_orderLog.value = true
}

// 打开工单附件弹窗
const showFiles = (row) => {
    dialogTable_orderFiles_title.value = "工单附件"
    dialogTable_orderFiles_type.value = 0
    currOrderFiles_orderId.value = row.orderId
    dialogTableVisible_orderFiles.value = true
}

// 打开施工档案弹窗
const showFilesEn = (row) => {
    dialogTable_orderFiles_title.value = "施工档案"
    dialogTable_orderFiles_type.value = 1
    currOrderFiles_orderId.value = row.orderId
    dialogTableVisible_orderFiles.value = true
}

// 确认已回款
const handleOrderPayment = (orderId) => {
    let form = {}
    form.orderId = orderId
    //1:未派发, 2:已派发,3工程师已接单，4工程师已出发，5:已开始,6施工已结束，7:已回款, 8:工单已完结
    form.orderStatus = 7
    const fun = api_orders_update(orderId, form)
    fun.then(res => {
        toast("操作成功")
        getData(false)
    })
}

// 确认结单
const handleOrderOver = (orderId) => {
    let form = {}
    form.orderId = orderId
    //1:未派发, 2:已派发,3工程师已接单，4工程师已出发，5:已开始,6施工已结束，7:已回款, 8:工单已完结
    form.orderStatus = 8
    const fun = api_orders_update(orderId, form)
    fun.then(res => {
        toast("操作成功")
        getData(false)
    })
}

//提交评价
const handleSubmit_score = () => {
    console.log(form_score)
    api_orders_postScore(form_score)
        .then(res => {
            toast('评价成功')
            formDrawerRef_score.value.close()
        })
        .catch(res => {
            // toastError('评价失败：' + res)
        })
}

// 查看项目详情
const loadProjectDetail = async () => {
    let projectInfo = await api_project_detail(props.projectId)
    //console.log("项目详情：", projectInfo)
    //项目详情
    resetForm_project(projectInfo.projectDto)
    //项目位置信息
    form_project.locationCreateDto = { ...projectInfo.projectLocationDto }
    address_project.value = projectInfo.projectLocationDto?.formattedAddress
    form_project.formattedAddress = projectInfo.projectLocationDto?.formattedAddress

    //项目客户信息
    checkedCustomer_project.value = projectInfo.customerDto
    //console.log("项目客户信息: ", JSON.stringify(checkedCustomer_project.value))
}

// 重置表单
function resetForm_project(row = false) {
    
    if (row) {
        for (const key in form_project) {
            form_project[key] = row[key]
        }
    }
}

//修改项目
function updateProject() {
    formRef_project.value.validate((valid) => {
        if (!valid) return
        let reqBody = { ...form_project }
        // 
        console.log('修改项目body: ', reqBody)
        api_project_update(props.projectId, reqBody)
            .then(res => {
                console.log('项目修改res: ', res)
                toast("项目信息修改成功")
            })
    })    
}

function updateProject_edit_flag() {
    form_project_edit_flag.value = !form_project_edit_flag.value
}

const emit = defineEmits([
    'deleteProject',
])

// 删除项目
function handleDelete_project() {
    api_project_delete(props.projectId).then(res => {
        toast("删除成功")
        emit('deleteProject')
    })
        
}


</script>